
from docx import Document

d = Document('测试.docx')
find_target = '粗体'
substitute = '粗体替换成功'


# 使用 Paragraph 对象的 runs 属性，替换文本可以不改变样式。
def replace_text(old_text, new_text):
    for p in d.paragraphs:
        if old_text in p.text:
            inline = p.runs
            for i in inline:
                if old_text in i.text:
                    text = i.text.replace(old_text, new_text)
                    i.text = text

if __name__ == '__main__':
    replace_text(find_target,substitute)
    d.save('测试2.docx')



